<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./../bootstrap/css/bootstrap.css">
  <style>
    .userphoto {
      width: 100px;
      height: 100px;
    }

    #myPage,
    #myPage2 {
      display: none;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="row">

      <div class="col">
        <h1 class="header">医生管理：</h1>
        <div class="my-5" class="row">
          <div class="col py-3">
            <form class="form-inline">
              <div class="input-group mb-2 mr-sm-2">
                <button class="btn btn-success form-control" type="button" id="addJobBtn">添加医生</button>
              </div>

              <label class="sr-only" for="dname">医生姓名:</label>
              <input type="text" class="form-control mb-2 mr-sm-2" id="dname" placeholder="请输入医生姓名">

              <label class="sr-only" for="jname">职称：</label>
              <div class="input-group mb-2 mr-sm-2">
                <select name="jname" class="form-control" id="jname">
                  <option value="1">医生</option>
                  <option value="2">主治医生</option>
                </select>
              </div>
              <label class="sr-only" for="dsex">职称：</label>
              <div class="input-group mb-2 mr-sm-2">
                <select name="dsex" class="form-control" id="dsex">
                  <option value="0" disabled selected>请选择性别</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
              <div class="input-group mb-2 mr-sm-2">
                <button class="btn btn-primary form-control" type="button" id="searchBtn">查询</button>
              </div>

            </form>
          </div>
        </div>
        <div>
          <table class="table table-hover table-bordered">
            <thead>
              <tr>
                <th>序号</th>
                <th>医生姓名</th>
                <th>职称名称</th>
                <th>性别</th>
                <th>身份证</th>
                <th>电话</th>
                <th>特长</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="doctorTable">
              <tr>
                <td>序号</td>
                <td>医生姓名</td>
                <td>主治医生</td>
                <td>性别</td>
                <td>身份证</td>
                <td>电话</td>
                <td>特长</td>
                <td>操作</td>
              </tr>

            </tbody>
          </table>
        </div>
        <!-- 分页 -->
        <div id="myPage">
          <nav>
            <ul class="pagination pagination-sm">
              <li class="page-item active" aria-current="page">
                <span class="page-link">1</span>
              </li>
              <li class="page-item"><a class="page-link" href="#">2</a></li>
              <li class="page-item"><a class="page-link" href="#">3</a></li>
            </ul>
            <!--   <select name="page" id="page"> -->
            <!-- <option value="5">5</option> -->
            <!-- </select> -->
          </nav>
        </div>
        <!--  搜索的分页 -->
        <div id="myPage2">
          <nav>
            <ul class="pagination pagination-sm">
              <!-- <li class="page-item active" aria-current="page">
                <span class="page-link">1</span>
              </li>
              <li class="page-item"><a class="page-link" href="#">2</a></li>
              <li class="page-item"><a class="page-link" href="#">3</a></li> -->
            </ul>
            <select name="page" id="page2">
              <!-- <option value="5">5</option> -->
            </select>
          </nav>
        </div>
      </div>
    </div>
  </div>
  <!-- 添加 -->
  <div class="modal" tabindex="-1" id="addDoctorModal">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加医生</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group row">
              <label for="dname2" class="col-sm-2 col-form-label">医生姓名：</label>
              <div class="col-sm-6">
                <input type="text" name="dname2" class="form-control" id="dname2" aria-describedby="emailHelp">
              </div>
              <div class="col-sm-4">
                <small id="dname2help" class="form-text text-muted">请输入20字以内</small>
              </div>
            </div>
            <div class="form-group row">
              <label for="dsid" class="col-sm-2 col-form-label">身份证号码：</label>
              <div class="col-sm-6"> <input type="text" name="dsid" class="form-control" id="dsid"
                  aria-describedby="emailHelp"></div>
              <div class="col-sm-4"><small id="dsidhelp" class="form-text text-muted">请输入18个字符</small></div>
            </div>
            <div class="form-group row">
              <label for="dtel" class="col-sm-2 col-form-label">电话号码：</label>
              <div class="col-sm-6"> <input type="text" name="dtel" class="form-control" id="dtel"
                  aria-describedby="emailHelp"></div>
              <div class="col-sm-4"><small id="dtelhelp" class="form-text text-muted">最多11个字符</small></div>
            </div>
            <div class="form-group row">
              <label for="dsex2" class="col-sm-2 col-form-label">性别：</label>
              <div class="col-sm-6">
                <select class="form-control" name="dsex2" id="dsex2">
                  <option value="" disabled selected>请选择</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
            </div>
            <div class="form-group row">
              <label for="dfeaturs" class="col-sm-2 col-form-label">医生特长：</label>
              <div class="col-sm-6"><textarea row="50" col="5" class="form-control" id="dfeaturs"></textarea></div>
              <div class="col-sm-4"> <small id="dfeaturshelp" class="form-text text-muted">50字以内</small></div>
            </div>
            <div class="form-group row">
              <label for="jid" class="col-sm-2 col-form-label">医生职称：</label>
              <div class="col-sm-6">
                <select class="form-control" name="jname" id="jid">
                  <option value="" disabled selected>请选择</option>
                  <option value="1">住院医生</option>
                </select>
              </div>
            </div>
            <div class="form-group row">
              <label for="dphoto" class="col-sm-2 col-form-label">头像：</label>
              <div class="col-sm-6">
                <input type="file" class="form-control" name="dphoto" id="dphoto" />
              </div>
              <div class="col-sm-4">
                <small id="dphotoshelp" class="form-text text-muted">选择图片，添加头像</small>
              </div>
            </div>
            <div class="form-group row">
              <label for="" class="col-sm-2 col-form-label"></label>
              <div class="col-sm-6">
                <img class="userphoto" src="./../img/userdefault.jpeg" alt="">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">返回</button>
          <button type="button" class="btn btn-primary btn-add">创建</button>
        </div>
      </div>
    </div>
  </div>

</body>
<script src="./../jquery/jquery 3.6.4.js"></script>
<script src="./../bootstrap/js/bootstrap.bundle.js"></script>

<script>
  let nowpage = 1, pagesize = 5, total = 0;
  let uphoto = null; // 头像file对象
  let jobs = []
  window.onload = function () {
    // console.log($.ajax);
    // 获取职称数据
    $.ajax({
      url: "/getJobs",
      type: 'get',
      success: function (res) {
        console.log(res)
        if (res.code === 200) {
          jobs = res.data;
          let jname = $('#jname');
          let jname2 = $("#jid")
          jname.html('');
          jname2.html('');

          let strHtml = '<option value="0" disabled selected>请选择职称</option>';

          res.data.forEach(el => {
            strHtml += `<option value="${el.jid}">${el.jname}</option>`;
          });
          jname.html(strHtml);
          jname2.html(strHtml);
        }

      }
    })

    // 获取默认一页的数据
    getDoctors(nowpage, pagesize);
  }
  // 案例： 多条件查询，

  const searchHandler = (nowpage, pagesize) => {
    let dname = $("#dname").val().trim();
    let jid = $("#jname").val();
    let dsex = $("#dsex").val();
    // console.log(dname, jname, dsex)

    if (!dname && !jid && !dsex) {
      alert('不能输入空格！请输入或选择一个查询条件')
      return;
    }

    $.ajax({
      url: '/searchDoctors',
      type: 'get',
      data: { dname, jid, dsex, nowpage, pagesize },
      success(res) {
        console.log(res)
        let doctorTable = $("#doctorTable")
        doctorTable.html('');
        let trHtml = "";
        res.data.forEach((el, index) => {
          trHtml += `<tr>
                <td>${index + 1}</td>
                <td>${el.dname}</td>
                <td>${el.jname}</td>
                <td>${el.dsex}</td>
                <td>${el.dsid}</td>
                <td>${el.dtel}</td>
                <td>${el.dfeaturs}</td>
                <td>
                  <button type="button" data-id="${el.did}" class="btn btn-sm btn-info btn-look">查看</button>
                  <button type="button" data-id="${el.did}" class="btn btn-sm btn-warning btn-edit">编辑</button> 
                  <button type="button" data-id="${el.did}" class="btn btn-sm btn-danger btn-delete">删除</button>   
                </td>
              </tr>`;
        })
        doctorTable.html(trHtml);

        // 分页：
        $("#myPage").hide()
        $("#myPage2").show()

        // 分页的动态渲染


      }

    })
  }

  // 搜索按钮绑定单击事件
  $("#searchBtn").on('click', function () {
    nowpage = 1;
    searchHandler(nowpage, pagesize)
  });

  // 添加医生，显示添加的modal界面：
  $("#addJobBtn").click(function () {
    console.log($("#addDoctorModal"))
    $("#addDoctorModal").modal('show');
  })

  // 创建医生
  $(".btn-add").click(function () {
    console.log("6666")
    let dname = $("#dname2").val();
    let dsid = $("#dsid").val();
    let dsex = $("#dsex2").val();
    let dfeaturs = $("#dfeaturs").val();
    let jid = $("#jid").val();
    let dtel = $("#dtel").val()

    let flag = true;
    // 验证表单

    if (flag === false) return;


    // 创建FormData()对象，把这个对象，做参数的数据对象，传给后端
    let formdata = new FormData()
    formdata.append('dname', dname);
    formdata.append('dsid', dsid);
    formdata.append('dsex', dsex)
    formdata.append('dfeaturs', dfeaturs)
    formdata.append('jid', jid);
    formdata.append('dtel', dtel)
    if (uphoto !== null) {
      formdata.append('dphoto', uphoto)
    }
    // 原生AJAX写法
    let xhr = new XMLHttpRequest();
    xhr.open('post', '/addDoctor', true)
    // xhr.setRequestHeader('content-type', 'multipart/form-data')  //不能写！
    xhr.send(formdata) //还是传formData对象做参数！！
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4 && xhr.status === 200) {
        let res = JSON.parse(xhr.responseText);
        if (res.code === 200) {
          alert('添加成功')
          $("#addDoctorModal").modal('hide');
        } else {
          alert('添加失败')
        }
      }
    }
    // jQuery.ajax()写法：
    /* 
        $.ajax({
          url: '/addDoctor',
          type: 'post',
          data: formdata, // formdata里面已经有key:value这些数据
          contentType: false, //不做编码变化
          processData: false, //不转化数据格式
          success(res) {
            console.log(res)
            if (res.code === 200) {
              $("#addDoctorModal").modal('hide');
    
              // 调用获取一页医生信息的接口，再渲染表格和分页。
    
            } else {
              alert('添加失败')
            }
          },
          fail(err) {
            console.log(err)
            console.log("fail")
          }
        })
    
     */
  })


  // 文件上传，头像选择功能
  $("#dphoto").change(function () {
    console.log(this.files[0])
    if (!this.files[0]) {
      uphoto = null;
      return;
    };
    uphoto = this.files[0]
    // 文件类型和文件大小的判断
    // 。。。
    let userphoto = $('.userphoto')

    // 本地图片的预览：
    let filereader = new FileReader();

    // 当编码转换结束后，触发的事件
    filereader.onload = function () {
      // console.log(filereader.result)
      userphoto.attr('src', filereader.result)
    }
    // 把文件对象，转为base64编码的字符串
    filereader.readAsDataURL(uphoto);
  });

  // 获取默认的医生数据
  const getDoctors = function (nowpage, pagesize) {
    $.ajax({
      url: "/getDoctors",
      type: 'get',
      data: { nowpage, pagesize },
      success(res) {
        if (res.code === 200) {
          let tabalData = res.data;
          renderTable(tabalData, "#doctorTable")  // 渲染表格
          let _total = Math.ceil(res.count / pagesize) //计算总页数
          // 分页：
          $("#myPage").show()
          $("#myPage2").hide()
          renderPagation_1(_total, '#myPage .pagination') //动态创建分页
        }
      }
    })
  }

  // 默认渲染表格
  const renderTable = (arr, selecter) => {
    let doctorTable = $(selecter)
    doctorTable.html('');
    let trHtml = "";
    arr.forEach((el, index) => {
      trHtml += `<tr>
                <td>${index + 1}</td>
                <td>${el.dname}</td>
                <td>${getJobNameByJid(el.jid)}</td>
                <td>${el.dsex}</td>
                <td>${el.dsid}</td>
                <td>${el.dtel}</td>
                <td>${el.dfeaturs}</td>
                <td>
                  <button type="button" data-id="${el.did}" class="btn btn-sm btn-warning btn-edit">编辑</button> 
                  <button type="button" data-id="${el.did}" class="btn btn-sm btn-danger btn-delete">删除</button>   
                </td>
              </tr>`;
    })
    doctorTable.html(trHtml);
  }

  // 从职称数据jobs里面，通过     jid 查找并返回 jname ，用于表格里面渲染职称，（如果后端值返回了医生数据，没有带职称数据时，要单独查询）
  const getJobNameByJid = (jid) => {
    let jname = ''
    jobs.forEach(el => {
      if (el.jid === jid) {
        jname = el.jname
      }
    })
    return jname;
  }

  /*
  渲染默认的分页的函数
  @params {Number} total 总页数
  @params {String} selecter 各种选择器
  */
  const renderPagation_1 = (total, selecter) => {
    // 分页的动态渲染
    let pageDom = $(selecter)
    pageDom.html('')
    liHtml = '';
    for (let i = 1; i <= total; i++) {
      console.log(nowpage == i)
      liHtml += `<li class="page-item ${nowpage == i ? 'active' : ''}" aria-current="page">
                <span class="page-link">${i}</span>
              </li>`;
    }
    pageDom.html(liHtml)
  }

  // 默认分页事件委托
  $('#myPage').on('click', '.page-item', function () {
    // console.log(this) // li
    nowpage = Number(this.innerText)
    getDoctors(nowpage, pagesize)
  })
</script>

</html>